package com.ngm.tea.t.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.ngm.tea.BaseController;
import com.ngm.tea.common.ExecuteResult;
import com.ngm.tea.common.PageInfo;
import com.ngm.tea.t.entity.Account;
import com.ngm.tea.t.entity.AccountRole;
import com.ngm.tea.t.entity.Role;
import com.ngm.tea.t.service.AccountRoleService;
import com.ngm.tea.t.service.AccountService;
import com.ngm.tea.t.service.RoleService;

/**
 * 控制器
 * @author zjw
 * @version 1.0
 * @date 2016-09-01 21:07:07
 *
 */
@Controller
@RequestMapping(value = "/t/account")
public class AccountController extends BaseController {
	
	public static final String FILE_SEPARATOR = System.getProperties().getProperty("file.separator");
	
	@Resource
	private AccountService thisService;
	@Resource
	private RoleService roleService;
	@Resource
	private AccountRoleService accountRoleService;
	private ExecuteResult executeResult = new ExecuteResult();
	private String viewPath = "App/t/account/";

	public AccountService getAccountService() {
		return thisService;
	}

	@Autowired
	public void setAccountService(AccountService thisService) {
		this.thisService = thisService;
	}

	@RequestMapping("/index")
	public String showAllList_E(Account account,PageInfo page, HttpServletRequest request) {
		try {
			PageInfo _pageInfo = new PageInfo(page.getPageCurrent(), page.getPageSize(), page.getOrderField(), page.getOrderDirection());
			List<Map<String, Object>> list = thisService.selectRll(account,_pageInfo);
			Long count = thisService.count(account);
			request.setAttribute("list", list);
			request.setAttribute("page", _pageInfo);
			request.setAttribute("account", account);
			request.setAttribute("count", count);
			return viewPath + "index";
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("InfoMessage", "信息载入失败！具体异常信息：" + e.getMessage());
			return "App/Admin/Common/result";
		}
	}
	
	@RequestMapping("/excel")
	public void excel(HttpServletRequest request, HttpServletResponse response) {
		String docsPath = request.getSession().getServletContext().getRealPath("docs");
		String fileName = "Account.xlsx";
		String filePath = docsPath + FILE_SEPARATOR + fileName;
		try {
			// 输出流
			OutputStream os = new FileOutputStream(filePath);
			// 工作区
			XSSFWorkbook wb = new XSSFWorkbook();
			XSSFSheet sheet = wb.createSheet("Account");// 创建第一个sheet
			XSSFRow row = sheet.createRow(0);// 生成表头
			row.createCell(0).setCellValue("标识");
			row.createCell(1).setCellValue("账户名称");
			
			List<Account> list = thisService.selectAll();
			for (int i = 0; i < list.size(); i++) {
				XSSFRow _row = sheet.createRow(i+1);// 生成行
				_row.createCell(0).setCellValue(list.get(i).getId());
				_row.createCell(1).setCellValue(list.get(i).getAccName());
			}
			// 写文件
			wb.write(os);
			// 关闭输出流
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		download(filePath, response);
	}
	
	@RequestMapping("/excelIds")
	public void excel(String ids, HttpServletRequest request, HttpServletResponse response) {
		String docsPath = request.getSession().getServletContext().getRealPath("docs");
		String fileName = "AccountIds.xlsx";
		String filePath = docsPath + FILE_SEPARATOR + fileName;
		try {
			// 输出流
			OutputStream os = new FileOutputStream(filePath);
			// 工作区
			XSSFWorkbook wb = new XSSFWorkbook();
			XSSFSheet sheet = wb.createSheet("Account");// 创建第一个sheet
			XSSFRow row = sheet.createRow(0);// 生成表头
			row.createCell(0).setCellValue("标识");
			row.createCell(1).setCellValue("账户名称");
			String[] _ids = ids.split(",");
			List<Account> list = new ArrayList<>();
			for(String id:_ids) {
				Account account = thisService.selectOne(Long.valueOf(id));
				list.add(account);
			}
			for (int i = 0; i < list.size(); i++) {
				XSSFRow _row = sheet.createRow(i+1);// 生成行
				_row.createCell(0).setCellValue(list.get(i).getId());
				_row.createCell(1).setCellValue(list.get(i).getAccName());
			}
			// 写文件
			wb.write(os);
			// 关闭输出流
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		download(filePath, response);
	}

	private void download(String path, HttpServletResponse response) {
		try {
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/vnd.ms-excel;charset=gb2312");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	@RequestMapping("/edit")
	public String modify(Long id, String roleName,HttpServletRequest request) {
		try {
			Account info = thisService.selectOne(id);
			List<Role> roles = roleService.selectAll();
			request.setAttribute("roleName", roleName);
			request.setAttribute("info", info);
			request.setAttribute("roles", roles);
			return viewPath + "edit";
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("InfoMessage", "信息载入失败！具体异常信息：" + e.getMessage());
			return viewPath + "result";
		}
	}

	@ResponseBody
	@RequestMapping("insert")
	public Object insert(Account info,String roleCode) {
		try {
			int id = thisService.insert(info);
			AccountRole accountRole = new AccountRole();
			accountRole.setAccCode(info.getAccCode());
			accountRole.setRoleCode(roleCode);
			accountRoleService.insert(accountRole);
			return executeResult.jsonReturn(200);
		} catch (Exception e) {
			e.printStackTrace();
			return executeResult.jsonReturn(300, e.getMessage());
		}
	}

	@ResponseBody
	@RequestMapping("update")
	public Object update(Account info,String roleCode) {
		try {
			thisService.update(info,roleCode);
			return executeResult.jsonReturn(200);
		} catch (Exception e) {
			e.printStackTrace();
			return executeResult.jsonReturn(300, e.getMessage());
		}
	}

	@ResponseBody
	@RequestMapping("/delete")
	public Object remove(Long id, HttpServletRequest request) {
		try {
			thisService.deleteById(id);
			return executeResult.jsonReturn(200, false);
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("InfoMessage", "信息载入失败！具体异常信息：" + e.getMessage());
			return executeResult.jsonReturn(300, e.getMessage());
		}
	}
	
	@ResponseBody
	@RequestMapping("/deleteids")
	public Object deleteByIds(String ids, HttpServletRequest request) {
		try {
			thisService.deleteByIds(ids);
			return executeResult.jsonReturn(200, false);
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("InfoMessage", "信息载入失败！具体异常信息：" + e.getMessage());
			return executeResult.jsonReturn(300, e.getMessage());
		}
	}
	
	/*
	 * 采用spring提供的上传文件的方法
	 */
	@ResponseBody
	@RequestMapping("springUpload")
	public Object springUpload(HttpServletRequest request) throws IllegalStateException, IOException {
		Map map = new HashMap<String,String>();
		long startTime = System.currentTimeMillis();
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					String path = request.getServletContext().getRealPath("/");
					String uploadPath = path + "upload/" + file.getOriginalFilename();
					// 上传
					file.transferTo(new File(uploadPath));
					map.put("statusCode", "200");
					map.put("filename", "upload/" + file.getOriginalFilename());
				}
			}
		}
		long endTime = System.currentTimeMillis();
		System.out.println("运行时间：" + String.valueOf(endTime - startTime) + "ms");
		return map;
	}
	
}